package com.example.spring.aop.aspect;

import com.example.spring.aop.annotation.RolesControl;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 对RolesControl注解 进行aop
 *
 * @author luowj12
 * @since 2021/6/7 9:55
 */
@Component
@Aspect
@Slf4j
public class RolesControlAspect {

    /**
     * @description 使用环绕通知
     */
    @Around("@annotation(com.example.spring.aop.annotation.RolesControl))")
    public Object doAround(ProceedingJoinPoint point) throws Throwable {
        Object res = null;
        MethodSignature methodSignature = (MethodSignature) (point.getSignature());
        Method targetMethod = methodSignature.getMethod();
        //url地址
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String url = request.getRequestURL().toString();
        String userid = request.getHeader("userid");

        if (targetMethod.isAnnotationPresent(RolesControl.class)) {
            RolesControl rolesControl = targetMethod.getAnnotation(RolesControl.class);
            String value = rolesControl.value();
            /*if(user.getInterfaceUrl()==null||!user.getInterfaceUrl().contains(url)){
                throw new BizException(ExceptionStatus.EXCEPTION_STATUS_0500.convert("没有权限!"));
            }*/
            if(value==null||value.equals(userid)){
                res = point.proceed();
            }else{
                res = "错误，权限不合格";
            }

        }
        return res;
    }

}
